import re


class RegexpReplacer(object):
    """
    功能：基于匹配的正则表达式替换单词;(英文缩写还原)
    形式：I should've done->I should have done
    调用：
        replacer = RegexpReplacer()
        s="I should've done that thing I didn't do"#s="can't is a contraction"#
        s1=replacer.replace(s)#->I should have done that thing I did not do
        print(s1)
    """
    def __init__(self):
        self.replacement_patterns=[
                (r'won\'t', 'will not'),
                (r'can\'t', 'can not'),
                (r'i\'m', 'i am'),(r'I\'m', 'I am'),
                (r'ain\'t', 'is not'),
                (r'(\w+)\'ll', '\g<1> will'),
                (r'(\w+)n\'t', '\g<1> not'),
                (r'(\w+)\'ve', '\g<1> have'),
                (r'(\w+)\'s', '\g<1> is'),
                (r'(\w+)\'re', '\g<1> are'),
                (r'(\w+)\'d', '\g<1> would')
            ]
        """基于匹配的正则表达式替换单词-缩写还原"""
        self.patterns = [(re.compile(regex), repl) for (regex, repl) in self.replacement_patterns]

    def replace(self, text):
        s = text
        for (pattern, repl) in self.patterns:
            s = re.sub(pattern, repl, s)
        return s


def txt_process(input_file,out_file):
    """功能：文本预处理（1.缩写还原；2.去除标点）
    形式：类似  wiki = WikiCorpus()的处理方式；
    如："help, i've lost my cellphone!" -> help i have lost my cellphone
    调用：
    input_file='data/clinc.txt'
    out_file='data/clinc_pro.txt'
    def txt_process(input_file,out_file)
    """
    with open(input_file, 'r') as f:
        vtext = f.read()
    #1.缩写还原
    replacer = RegexpReplacer()
    vtext=replacer.replace(vtext)#->I should have done that thing I did not do
    ##2.去除标点
    vtext = re.sub(r'[^\w\s]','',vtext)
    with open(out_file, 'w') as f:  # with方式不用关闭
        f.write(str(vtext))
        print(f"保存文件：{out_file}")